package com.virgo.demo.support.controller.admin;

import cn.hutool.crypto.SecureUtil;
import com.virgo.common.entity.IResponse;
import com.virgo.demo.core.utils.CaptchaUtils;
import com.virgo.demo.support.service.AppService;
import com.virgo.redis.service.CacheService;
import com.virgo.web.utils.IFileUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@RestController
@RequestMapping("/manage168/simple")
@RequiredArgsConstructor
public class SimpleController {

    private final IFileUtils iFileUtils;

    private final AppService appService;

    private final CacheService cacheService;

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public IResponse<HashMap<String, String>> uploadAction(@RequestParam("file") MultipartFile file) {
        String filePath = iFileUtils.upload("upload",file);
        HashMap<String, String> data = new HashMap<>();
        data.put("src",filePath);
        data.put("showUrl",appService.getStaticUrl(filePath));
        return IResponse.ok(data);
    }

    @RequestMapping(value = "/captcha",method = RequestMethod.GET)
    public void captchaAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = CaptchaUtils.generateVerifyCode(4);
        int w = 200, h = 100;
        CaptchaUtils.outputImage(w, h, response.getOutputStream(), code);
        String cacheKey = request.getParameter("captchaKey");
        if (!ObjectUtils.isEmpty(cacheKey)) {
            cacheKey = SecureUtil.md5(cacheKey);
            cacheService.set(cacheKey,code.toLowerCase(),600L);
        }
    }
}